#!/usr/bin/python2.4
#
#Copyright 2009 Google Inc.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
#


"""Tests for the module page_tree_utils."""

import logging
import unittest
from google.appengine.ext import db
import db_utils
from metadata_handler import UploadMetadataHandler
from metadata_in_memory import MetadataInMemory
import page_tree_utils
import text_data_reader
from tree_node import PageTree


class Request(object):
  """Dummy Request class."""
  uri = ''


class Response(object):
  """Dummy Response class."""

  class Out(object):
    """Dummy Out class for the Response object."""
    text = ''

    def write(self, st):
      """Dummy write response method.

      Args:
        st: String html response.
      """
      self.text = st
  out = Out()


class PageTreeUtilsTest(unittest.TestCase):
  """Test for the class PageTreeUtils."""

  def setUp(self):
    """Set up method."""
    logging.info('TEST: ' + self.id())
    self.db_handler = db_utils.DbHandler()
    self.metadata_in_memory = MetadataInMemory()
    self.page_tree = PageTree()

  def PrepareDb(self, version_id):
    """Write metadata into db.

    Args:
      version_id: Version id number.
    """
    f = open('test/data/metadata_valid.txt', 'r')
    text_data_reader.ReadMetadataFile(f, version_id)
    f.close()
    self.upload_metadata_handler = UploadMetadataHandler()
    self.upload_metadata_handler.request = Request()
    self.upload_metadata_handler.request.uri = 'http://localhost:8080'
    self.upload_metadata_handler.response = Response()
    self.upload_metadata_handler.get()
    while True:
      out_text = self.upload_metadata_handler.response.out.text
      if out_text.find('/uploadmetadata') != -1:
        self.upload_metadata_handler = UploadMetadataHandler()
        self.upload_metadata_handler.request = Request()
        self.upload_metadata_handler.request.uri = 'http://localhost:8080'
        self.upload_metadata_handler.response = Response()
        self.upload_metadata_handler.get()
      else:
        return

  def testGetAllRows(self):
    """Tests the method GetAllRows."""
    version_id = self.db_handler.CreateNewVersion()
    self.PrepareDb(version_id)
    self.page_tree_utils_instance = page_tree_utils.GQLUtils(version_id)
    rows = self.page_tree_utils_instance.GetAllRows()
    count = 10
    for row in rows:
      metadata_row = self.db_handler.GetMetadataById(version_id, row[0])
      self.assertNotEqual(metadata_row, None)
      self.assertEqual(row[0], metadata_row[0])
      self.assertEqual(row[1], metadata_row[1])
      self.assertEqual(row[2], metadata_row[2])
      self.assertEqual(row[3], metadata_row[3])
      self.assertEqual(row[4], metadata_row[4])
      count -= 1
      if not count:
        break
    self.db_handler.RemoveVersion(version_id)
    self.metadata_in_memory.Clear()

  def testGetMetadataRowByNumber(self):
    """Test the method GetMetadataByRowNumber."""
    rows = [1, 2, 3, 4]
    version_id = self.db_handler.CreateNewVersion()
    self.PrepareDb(version_id)
    self.page_tree_utils_instance = page_tree_utils.GQLUtils(version_id)
    for row in rows:
      fields = self.page_tree_utils_instance.GetMetadataRowByNumber(row)
      q = db.GqlQuery(
          'SELECT * FROM Metadata WHERE version_id=:1 AND row_id=:2',
          version_id, row)
      r = q.fetch(1)
      self.assertEqual(r[0].id, fields[0])
      self.assertEqual(r[0].sorting_column1, fields[1])
      self.assertEqual(r[0].sorting_column2, fields[2])
      self.assertEqual(r[0].sorting_column3, fields[3])
      self.assertEqual(r[0].title, fields[4])
      self.assertEqual(r[0].rest_metadata, '\t'.join(fields[5:]))
    self.db_handler.RemoveVersion(version_id)
    self.metadata_in_memory.Clear()
    self.page_tree.Clear()


def main(unused_argv):
  unittest.main()
